/**
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import ConfigData from '../../../../../../common/utils/src/main/ets/default/baseUtil/ConfigData';
import LogUtil from '../../../../../../common/utils/src/main/ets/default/baseUtil/LogUtil';
import Ability from '@ohos.application.Ability'
import display from '@ohos.display';
import screen from '@ohos.screen';
import CommonEvent from '@ohos.commonEvent';
import settings from '@ohos.settings';

//HDMI
const SETTINGS_RESOLUTION = "settings.resolution";
const URI_VAR = 'datashare:///com.ohos.settingsdata.DataAbility';

export default class MainAbility extends Ability {
    async onCreate(want, launchParam) {
        LogUtil.info(ConfigData.TAG + 'Application onCreate ===> want: ' + JSON.stringify(want))
        globalThis.abilityWant = want;
        globalThis.AbilityLauncherParam = launchParam
        globalThis.settingsAbilityContext = this.context;

        globalThis.resolution = settings.getValueSync(globalThis.settingsAbilityContext, SETTINGS_RESOLUTION, "err");
        console.log("=-= get curResolution: "+JSON.stringify(globalThis.curResolution));
    }

    onNewWant(want, launchParams) {
        LogUtil.info(ConfigData.TAG + `onNewWant. want: ${JSON.stringify(want)}, launchParams: ${JSON.stringify(launchParams)}`)

        globalThis.abilityWant = want;
        globalThis.AbilityLauncherParam = launchParams

        let param: [string: any] = globalThis.abilityWant.parameters
        LogUtil.info(ConfigData.TAG + 'onNewWant ===> param: ' + JSON.stringify(param))
        if (param['pageUrl'] == 'ETH') {
            globalThis.windowStage.setUIContent(this.context, "pages/network/wiredNetwork", null)
        }else if (param['pageUrl'] == 'BLUETOOTH') {
            globalThis.windowStage.setUIContent(this.context, "pages/bluetooth/bluetooth", null)
        }else if (param['pageUrl'] == 'WIFI') {
            globalThis.windowStage.setUIContent(this.context, "pages/network/wifi", null)
        }else {
            globalThis.windowStage.setUIContent(this.context, "pages/settingList", null)
        }
    }

    onDestroy() {
        AppStorage.SetOrCreate('settingsList', []);
        LogUtil.info(ConfigData.TAG + 'Application onDestroy')
    }

    async onWindowStageCreate(windowStage) {
        // Main window is created, set main page for this ability
        LogUtil.log("[Main] MainAbility onWindowStageCreate")

        globalThis.windowStage = windowStage

        globalThis.screenWidth = (await this.getWindowDisplayData()).width
        globalThis.screenHeight = (await this.getWindowDisplayData()).height
        LogUtil.info(ConfigData.TAG + 'screenWidth: ' + globalThis.screenWidth + ' screenHeight: ' + globalThis.screenHeight);

        let param: [string: any] = globalThis.abilityWant.parameters
        LogUtil.info(ConfigData.TAG + 'onWindowStageCreate ===> param: ' + JSON.stringify(param))
        if (param['pageUrl'] == 'ETH') {
            windowStage.setUIContent(this.context, "pages/network/wiredNetwork", null)
        }else if (param['pageUrl'] == 'BLUETOOTH') {
            windowStage.setUIContent(this.context, "pages/bluetooth/bluetooth", null)
        }else if (param['pageUrl'] == 'WIFI') {
            windowStage.setUIContent(this.context, "pages/network/wifi", null)
        }else {
            windowStage.setUIContent(this.context, "pages/settingList", null)
        }

        //监听横竖屏切换
        screen.on("change",async(code)=>{
            globalThis.screenWidth = (await this.getWindowDisplayData()).width
            globalThis.screenHeight = (await this.getWindowDisplayData()).height
            console.info(`SettingScreen:width=>${ globalThis.screenWidth},height==>${ globalThis.screenHeight}`)
            AppStorage.SetOrCreate("IsVertical", globalThis.screenWidth<globalThis.screenHeight)
        })
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        LogUtil.log("[Main] MainAbility onWindowStageDestroy")
    }

    onForeground() {
        // Ability has brought to foreground
        LogUtil.log("[Main] MainAbility onForeground")

        CommonEvent.publish("SETTINGS_FOREGROUND", (err) => {
            if (err.code) {
                LogUtil.info(ConfigData.TAG + 'onForeground publish SETTINGS_FOREGROUND err: ' + JSON.stringify(err));
            } else {
                LogUtil.info(ConfigData.TAG + 'onForeground publish SETTINGS_FOREGROUND success')
            }
        });

        // 当Settings在前台时，销毁Settings_Menu
        var want = {
            bundleName: "com.ohos.settings",
            abilityName: "com.ohos.settings.menu.ServiceAbility"
        };
        globalThis.settingsAbilityContext.stopServiceExtensionAbility(want, (error) => {
            if (error.code) {
                // 处理业务逻辑错误
                LogUtil.info(ConfigData.TAG + 'onForeground stopServiceExtensionAbility err: ' + JSON.stringify(error));
                return;
            }
            // 执行正常业务
            console.log('stopServiceExtensionAbility succeed');
        });
    }

    onBackground() {
        // Ability has back to background
        LogUtil.log("[Main] MainAbility onBackground")

        CommonEvent.publish("SETTINGS_BACKGROUND", (err) => {
            if (err.code) {
                LogUtil.info(ConfigData.TAG + 'onForeground publish SETTINGS_BACKGROUND err: ' + JSON.stringify(err));
            } else {
                LogUtil.info(ConfigData.TAG + 'onForeground publish SETTINGS_BACKGROUND success')
            }
        });
    }

    private async getWindowDisplayData() {
        let displayData: display.Display = null;
        await display.getDefaultDisplay()
            .then((res)=>{
                displayData = res;
            }).catch((err)=>{
                LogUtil.error(ConfigData.TAG + 'getWindowDisplayData error:' + err);
            });
        return displayData;
    }
};
